﻿using System.Configuration;
using System.Data.SqlClient;
using System.Reflection;

namespace Tisbi.LawFirm.BL
{
    public static class ConfigurationHelper
    {
        public const string ConnectionStringNameKey = "LawContext";

        public static void UpdateConnectionString(string connectionString)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            int? conIndex = null;
            for (int i = 0; i < config.ConnectionStrings.ConnectionStrings.Count; i++)
            {
                ConnectionStringSettings connectionStringSettings = config.ConnectionStrings.ConnectionStrings[i];
                if (connectionStringSettings.Name != ConnectionStringNameKey)
                {
                    continue;
                }

                conIndex = i;
                break;
            }

            if (conIndex.HasValue)
            {
                config.ConnectionStrings.ConnectionStrings[conIndex.Value].ConnectionString = connectionString;
                config.ConnectionStrings.ConnectionStrings[conIndex.Value].Name = ConnectionStringNameKey;
                config.ConnectionStrings.ConnectionStrings[conIndex.Value].ProviderName = "System.Data.EntityClient";
            }
            else
            {
                config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings
                {
                    ConnectionString = connectionString,
                    Name = ConnectionStringNameKey,
                    ProviderName = "System.Data.EntityClient"
                });
            }
            
            config.Save(ConfigurationSaveMode.Full, true);
            ConfigurationManager.RefreshSection("connectionStrings");
        }

        public static ConnectionStringSettings GetConnectionString()
        {
            var count = ConfigurationManager.ConnectionStrings.Count;
            if (count == 0)
            {
                return null;
            }

            try
            {
                ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringNameKey];
                return connectionString;
            }
            catch
            {
                return null;
            }
        }

        public static SqlConnectionStringBuilder GetConnectionStringAsBuilder()
        {
            var connectionString = GetConnectionString();
            if (connectionString == null)
            {
                return null;
            }

            var builder = new SqlConnectionStringBuilder(connectionString.ConnectionString);
            return builder;
        }
    }
}
